<?php
defined('weiboCookie') || define('weiboCookie',dirname(__FILE__).'/weibodata/weibocookie.txt');


/**
 * 新浪微博 OAuth 认证类(OAuth2)
 *
 * 授权机制说明请大家参考微博开放平台文档：{@link http://open.weibo.com/wiki/Oauth2}
 *
 * @package sae
 * @author Elmer Zhang
 * @version 1.0
 */
class weibo extends SaeTOAuthV2 {
	
	function __construct($client_id, $client_secret, $access_token = NULL, $refresh_token = NULL) {
		parent::__construct($client_id, $client_secret, $access_token , $refresh_token );
	}

	function authorizeLogin(){
		//prelogin
		$preloginTime=floor(microtime(true)*1000);
		$preloginUrl="https://login.sina.com.cn/sso/prelogin.php?entry=openapi&callback=sinaSSOController.preloginCallBack&su=".base64_encode(WB_USER)."&client=ssologin.js(v1.3.22)&_=".$preloginTime;
		$preloginStr=$this->http($preloginUrl,"GET");

		//login
		$prelt=intval(floor(microtime(true)*1000)-$preloginTime);
		preg_match('#sinaSSOController.preloginCallBack\((.*?)\)#i',$preloginStr,$match);
		$jsonArr = json_decode($match[1], true);
		if($jsonArr["retcode"]!=0){
			echo 'prelogin error!<br />';
			exit;
		}
		$su = base64_encode(urlencode(WB_USER));
		$servertime = $jsonArr['servertime'];
		$pcid = $jsonArr['pcid'];
		$nonce = $jsonArr['nonce'];
		$sp = sha1(sha1(sha1(WB_PASS)) . $servertime . $nonce);
		$loginTime=floor(microtime(true)*1000);
		$loginUrl="https://login.sina.com.cn/sso/login.php?entry=openapi&gateway=1&from=&savestate=0&useticket=1&ct=1800&s=1&vsnf=1&vsnval=&door=&su=".$su."&service=miniblog&servertime=".$servertime."&nonce=".$nonce."&pwencode=wsse&sp=".$sp."&encoding=UTF-8&callback=sinaSSOController.loginCallBack&cdult=2&domain=weibo.com&prelt=".$prelt."&returntype=TEXT&client=ssologin.js(v1.3.22)&_=".$loginTime;
		$loginStr=$this->http($loginUrl,"GET");

		//authorize
		preg_match('#sinaSSOController.loginCallBack\((.*?)\);#i',$loginStr,$match);
		$jsonArr = json_decode($match[1], true);
		if($jsonArr["retcode"]!=0){
			var_dump($jsonArr);
			echo 'login error:'.$jsonArr["reason"];
			exit;
		}
		$retcode=$jsonArr['retcode'];
		$ticket=$jsonArr['ticket'];
		$uid=$jsonArr['uid'];
		$crossDomainUrlList=$jsonArr['crossDomainUrlList'];
		$ticket=urlencode($ticket);
		$callback=urlencode(WB_CALLBACK_URL);
		$authorizeUrl='https://api.weibo.com/oauth2/authorize';
		$postStr='action=submit&withOfficalFlag=0&ticket='.$ticket.'&isLoginSina=&response_type=code&regCallback=&redirect_uri='.$callback.'&client_id='.WB_AKEY.'&state=&from=&userId='.WB_USER.'&passwd=';
		$this->http($authorizeUrl,"POST",$postStr);

		//weibo login page
		$refer="https://api.weibo.com/oauth2/authorize?client_id=".WB_AKEY."&redirect_uri=".urlencode(WB_CALLBACK_URL)."&response_type=code";
		$this->http($refer,"GET");
		
		$location=empty($this->http_header["location"]) ? false : $this->http_header["location"];
		$token=false;
		if($location){
			$query = parse_url($location,PHP_URL_QUERY);
			$query = explode('=',$query);
			$code = $query[1];

			$keys = array();
			$keys['code'] = $code;
			$keys['redirect_uri'] = WB_CALLBACK_URL;
			try{
				$token = $this->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {
				
			}
		}
		
		return $token;
	}

	function loginweibo(){
		$preLoginData = $this->http('http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su='.base64_encode(WB_USER).'&client=ssologin.js(v1.3.16)', 'GET');
		preg_match('/sinaSSOController.preloginCallBack\((.*)\)/', $preLoginData, $preArr);
		$jsonArr = json_decode($preArr[1], true);
		if($jsonArr){
			$postArr = array(
				'entry' => 'weibo',
				'gateway' => 1,
				'from' => '',
				'vsnval' => '',
				'savestate' => 7,
				'useticket' => 1,
				'ssosimplelogin' => 1,
				'su' => base64_encode(urlencode(WB_USER)),
				'service' => 'miniblog',
				'servertime' => $jsonArr['servertime'],
				'nonce' => $jsonArr['nonce'],
				'pwencode' => 'wsse',
				'sp' => sha1(sha1(sha1(WB_PASS)) . $jsonArr['servertime'] . $jsonArr['nonce']),
				'encoding' => 'UTF-8',
				'url' => 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
				'returntype' => 'META'
			);
			$loginData = $this->http('http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.19)','POST', $postArr);
			if($loginData){
				$matchs = array();
		   
				preg_match('/replace\(\'(.*?)\'\)/', $loginData, $matchs);
				$loginResult = $this->http($matchs[1], 'GET');

				$loginResultArr = array();
				preg_match('/feedBackUrlCallBack\((.*?)\)/', $loginResult, $loginResultArr);
				$userInfo = json_decode($loginResultArr[1],true);
				
				return $userInfo;
			}else{
				echo ("login sina fail!");
				exit;
			}
		}else{
			echo ("server tickit fail!");
			exit;
		}
	}

	/**
	 * Make an HTTP request
	 *
	 * @return string API results
	 * @ignore
	 */
	function http($url, $method, $postfields = NULL, $headers = array()) {
		$this->http_info = array();
		$ci = curl_init();
		/* Curl settings */
		if(preg_match('#^https#i',$url,$match)){
			curl_setopt($ci, CURLOPT_PORT , 443);
		}
		curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
		curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
		curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
		curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ci, CURLOPT_ENCODING, "");
		curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
		curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, $this->ssl_verifypeer);
		curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
		curl_setopt($ci, CURLOPT_HEADER, FALSE);
		curl_setopt($ci, CURLOPT_COOKIEFILE,weiboCookie); 
		curl_setopt($ci, CURLOPT_COOKIEJAR,weiboCookie);

		switch ($method) {
			case 'POST':
				curl_setopt($ci, CURLOPT_POST, TRUE);
				if (!empty($postfields)) {
					curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
					$this->postdata = $postfields;
				}
				break;
			case 'DELETE':
				curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
				if (!empty($postfields)) {
					$url = "{$url}?{$postfields}";
				}
		}

		if ( isset($this->access_token) && $this->access_token )
			$headers[] = "Authorization: OAuth2 ".$this->access_token;

		$headers[] = "API-RemoteIP: " . $_SERVER['REMOTE_ADDR'];
		curl_setopt($ci, CURLOPT_URL, $url );
		curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
		curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );

		$response = curl_exec($ci);
		$this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
		$this->http_info = array_merge($this->http_info, curl_getinfo($ci));
		$this->url = $url;

		if ($this->debug) {
			//echo "=====post data======\r\n";
			//var_dump($postfields);

			//echo '=====info====='."\r\n";
			//print_r( curl_getinfo($ci) );

			echo '=====$response====='."\r\n";
			print_r( $response );
		}
		curl_close ($ci);
		return $response;
	}
}

